
"""
    菜单
"""

from rest_framework import serializers
from users.models import Menu


class MenuSerializer(serializers.ModelSerializer):
    """
    导航菜单序列化
    """

    class Meta:
        model = Menu
        fields = ('id', 'name', 'icon', 'path', 'is_show', 'is_frame', 'sort', 'component', 'pid')


class MenuModelListSerializer(serializers.ModelSerializer):
    """
    菜单列表序列化
    """

    class Meta:
        model = Menu
        fields = ('id', 'name', 'icon', 'path', 'is_show', 'is_frame', 'sort', 'component', 'pid')


class MenuModelRetrieveSerializer(serializers.ModelSerializer):
    """
    菜单详情序列化
    """

    class Meta:
        model = Menu
        fields = ('id', 'name', 'icon', 'path', 'is_show', 'is_frame', 'sort', 'component', 'pid')

    def to_representation(self, instance):
        """
        修改序列化前的数据格式
        :param instance:
        :return:
        """
        data = super().to_representation(instance)
        # pid 父级菜单(限制5层)
        if data['id']:
            mid = Menu.objects.filter(id=data['id']).first()
            if mid.pid:
                data['pid'] = [mid.pid.id]
                if mid.pid.pid:
                    data['pid'] = [mid.pid.pid.id, mid.pid.id]
                    if mid.pid.pid.pid:
                        data['pid'] = [mid.pid.pid.pid.id, mid.pid.pid.id, mid.pid.id]
                        if mid.pid.pid.pid.pid:
                            data['pid'] = [mid.pid.pid.pid.pid.id, mid.pid.pid.pid.id, mid.pid.pid.id, mid.pid.id]
        return data
